package com.mm.handlers;


import com.mm.annotation.Login;
import com.mm.annotation.Wdx;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 反射获取方法上的Login注解
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Wdx annotation = handlerMethod.getMethod().getAnnotation(Wdx.class);
        if (annotation != null){
            System.out.println(annotation.description());
        }
        Login login = handlerMethod.getMethod().getAnnotation(Login.class);
        if(login == null){
            return true;
        }

        // 有Login注解说明需要登录，提示用户登录
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().print("你访问的资源需要登录");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {

    }
}
